import jwtSign from "@/common/jwt";
import  {Toast}  from '@nutui/nutui';
// import '@nutui/nutui/dist/packages/toast/style';
import _ from "lodash";
import { useStore as useUserStore } from "@/store/user";

export default class apibase {
  constructor() {

  }
  // api请求公共方法
  base(instance: any) {
    instance.defaults.baseURL = process.env.VUE_APP_BASE_API;
    /**
     * @Auther: 罗耀祖
     * @LastEditors: 罗耀祖
     * @description: 请求拦截添加公共参数
     */
    instance.interceptors.request.use((config: any) => {
      config.timeout = 8000;
      return config;
    })
    /**
     * @Auther: 罗耀祖
     * @LastEditors: 罗耀祖
     * @description: 回传拦截处理回传内容
     */
    instance.interceptors.response.use((response: any) => {
      let res = { code: response.data.code, msg: response.data.msg, data: response.data.data };
      return this.matchRes(res);
    }, (error: any) => {
      error = JSON.parse(JSON.stringify(error));
      if (error?.response) {
        console.error(error);
      } else {
        Toast.fail(error.message);
      }
      return Promise.reject(error);
    })
  }
  // res 回传结果, async 是否异步
  matchRes = (res: any) => {
    if (res.code === 200) {
      return res;
    } else if (res.code === 400) {
      Toast.fail(res.msg);
      return Promise.reject(res);
    } else if (res.code === 401) {
      Toast.fail(res.msg);
      const userStore = useUserStore();
      userStore.setLoginInfo({
        token: "",
        uid: "",
      })
      return Promise.reject(res);
    } else if (res.code === 403) {
      Toast.fail(res.msg);
      return Promise.reject(res);
    } else if (res.code === 500) {
      return Promise.reject(res);
    } else {
      return Promise.reject(res);
    }
  }
  //type: jwt验签请求   upload:上传
  get({ url, instance, data, type = "jwt" }: { url: string, instance: any, data: any, type?: string}) {
    instance.interceptors.request.use((config: any) => {
      if (type === "jwt") {
        const userStore = useUserStore();
        const token = userStore.login_info.token;
        const uid =  userStore.login_info.uid;
        let Authorization: any = {
          iat: (new Date().getTime() / 1000).toFixed(0),
          ...data,
          token,
          uid,
        };
        console.log("get",Authorization)
        Authorization = jwtSign(Authorization);
        config.headers.Authorization = Authorization;
      }
      return config;
    });
    this.base(instance);
    return instance.get(url, { params: data });
  }
  //type: jwt验签请求   upload:上传
  post({ url, instance, data, type = "jwt", formData }: { url: string, instance: any, data: any, type?: string,formData?: any }) {
    const mData = _.cloneDeep(data);
    instance.interceptors.request.use((config: any) => {
      if (type === "jwt") {
        const userStore = useUserStore();
        const token = userStore.login_info.token;
        const uid =  userStore.login_info.uid;

        let Authorization: any = {
          iat: (new Date().getTime() / 1000).toFixed(0),
          ...mData,
          token,
          uid,
        };
        console.log("post",Authorization)
        Authorization = jwtSign(Authorization);
        config.headers.Authorization = Authorization;
      }
      return config;
    });
    this.base(instance);
    if (formData) {
      const form = new FormData();
      Object.entries(data).forEach((item: any) => {
        form.append(item[0], item[1]);
      })
      Object.entries(formData).forEach((item: any) => {
        form.append(item[0], item[1]);
      })
      data = form;
    }

    return instance.post(url, data);
  }
}